package com.tamecode.beanfactory;

import com.tamecode.reflect.Car;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class BeanLifeCycle {

    private static void lifeCycleInBeanFactory() {
        // 1.下面两句装载配置文件并启动容器
        Resource resource = new ClassPathResource("beans.xml");
        BeanFactory beanFactory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((DefaultListableBeanFactory) beanFactory);
        reader.loadBeanDefinitions(resource);

        // 2.向容器注册 MyBeanPostProcessor 后处理器
        ((DefaultListableBeanFactory) beanFactory).addBeanPostProcessor(new MyBeanPostProcessor());

        // 3.向容器注册 MyInstantiationAwareBeanProcessor 后处理器
        ((DefaultListableBeanFactory) beanFactory).addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());

        // 4.第一次从容器中获取 Car，将触发容器实例化广该 Bean，这将引发 Bean 生命周期方法的调用
        Car car1 = (Car) beanFactory.getBean("car");
        car1.introduce();
        car1.setColor("红色");

        // 5.第二次从容器中获取Car，直接从缓存池中获取
        Car car2 = (Car) beanFactory.getBean("car");
        // 6.查看 car1 和 car2 是否是指向同一引用
        System.out.println("car1 == car2:" + (car1 == car2));

        // 7.关闭容器
        ((DefaultListableBeanFactory) beanFactory).destroySingletons();
    }

    public static void main(String[] args) {
        lifeCycleInBeanFactory();
    }

}
